package config

import (
	"context"
	"net/http"

	"go-zero-admin/apps/system/cmd/api/internal/svc"
	"go-zero-admin/apps/system/cmd/api/internal/types"
	"go-zero-admin/apps/system/cmd/rpc/syspb"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
)

type ListConfigLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	r      *http.Request
}

func NewListConfigLogic(ctx context.Context, svcCtx *svc.ServiceContext, r *http.Request) *ListConfigLogic {
	return &ListConfigLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		r:      r,
	}
}

func (l *ListConfigLogic) ListConfig(req *types.ListConfigReq) (resp *types.ListConfigResp, err error) {
	configListResp, err := l.svcCtx.ConfigRpc.GetConfigList(l.ctx, &syspb.GetConfigListReq{
		Page: &syspb.PageReq{
			DateRange: req.DateRange,
			PageNum:   req.PageNum,
			PageSize:  req.PageSize,
			IsPage:    true,
		},
		ConfigName: req.ConfigName,
		ConfigKey:  req.ConfigKey,
		ConfigType: req.ConfigType,
	})
	if err != nil {
		return nil, err
	}

	// 处理数据
	configList := make([]*types.SysConfig, 0)
	for _, v := range configListResp.GetList() {
		var config types.SysConfig
		_ = copier.Copy(&config, v)
		configList = append(configList, &config)
	}

	return &types.ListConfigResp{
		PageResp: &types.PageResp{
			CurrentPage: configListResp.GetPage().GetCurrent(),
			Total:       configListResp.GetPage().GetTotal(),
		},
		List: configList,
	}, nil
}
